package com.tjbklx1.thread.chap04.practise04;

import java.util.LinkedList;
import java.util.Queue;

import com.tjbklx1.thread.chap03.demo01.Request;

public class RequestQueue2 {

	private final Queue<Request> queue = new LinkedList<Request>();
	private static final long TIMEOUT = 30000L;

	public synchronized Request getRequest() { // 注意同步
		long now = System.currentTimeMillis();
		while (queue.peek() == null) {
			long start = System.currentTimeMillis();
			long rest = TIMEOUT-(now-start);
			if(rest<=0){
				throw new LivenessException("throw by :"+Thread.currentThread().getName());
			}
			
			try {
//				System.out.println(Thread.currentThread().getName() + " : wait() begins,queue = " + queue);
				wait();
//				System.out.println(Thread.currentThread().getName() + " : wait() ends,queue = " + queue);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return queue.remove();
	}

	public synchronized void putRequest(Request request) { // 注意同步
		queue.offer(request);
		System.out.println(Thread.currentThread().getName() + " : notifyAll() begins,queue = " + queue);
		notifyAll();
		System.out.println(Thread.currentThread().getName() + " : notifyAll() ends,queue = " + queue);
	}
}
